package com.conan.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.InputStream;

public class AliOssUtil {
    //这四个一般不变，所以抽取到成员处，声明为静态常量
    public static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";//区域节点
    public static final String ACCESS_KEY_ID="LTAI5tPuAVxjLBAMg3PSpxWJ";
    public static final String ACCESS_KEY_SECRET="TfoEn38o8pgO9btABuZwop89arVSaD";
    public static final String BUCKET_NAME = "big-event-bucket10086";// Bucket名称

    // objectName: 要存储的对象的名称，这里的对象可以是字符串、图片、视频等
    // 方法内部可能发生变化的是objectName和输入流，因此以参数的方式暴露出去
    // 方法要返回图片在服务器上的访问地址，因此返回值是String类型
    public static String upLoadFile(String objectName, InputStream inputStream) throws Exception {

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        String url = ""; //为了返回url，先声明一个空字符串
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, inputStream);
            PutObjectResult result = ossClient.putObject(putObjectRequest);//上传到服务器
            //如果下面的代码不报错，就该给url赋值了
            //url组成：https://bucket名称.区域节点(去掉https://)/objectName
            //ENDPOINT.lastIndexOf("/")+1: 在ENDPOINT中，从最后一个"/"的下一个位置开始截取字符串
            url="https://"+BUCKET_NAME+"."+ENDPOINT.substring(ENDPOINT.lastIndexOf("/")+1)+"/"+objectName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}

